#!/usr/bin/env node

// SimpleNote 构建脚本
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

class BuildManager {
  constructor() {
    this.buildConfig = {
      compilationKey: process.env.COMPILATION_KEY || this.generateRandomKey(),
      versionId: process.env.VERSION_ID || 'v1.0.0',
      distribution: process.env.DISTRIBUTION || 'public',
      buildTime: new Date().toISOString(),
      buildId: this.generateBuildId()
    };
    
    this.sourceDir = __dirname;
    this.distDir = path.join(__dirname, 'dist');
  }

  // 生成随机密钥
  generateRandomKey() {
    return crypto.randomBytes(32).toString('hex');
  }

  // 生成构建ID
  generateBuildId() {
    return crypto.randomBytes(8).toString('hex');
  }

  // 主构建方法
  async build() {
    console.log('🚀 开始构建 SimpleNote...');
    console.log(`📦 版本: ${this.buildConfig.versionId}`);
    console.log(`🔑 分发: ${this.buildConfig.distribution}`);
    console.log(`⏰ 构建时间: ${this.buildConfig.buildTime}`);
    
    try {
      // 创建构建目录
      this.createBuildDir();
      
      // 注入配置
      await this.injectConfig();
      
      // 复制静态文件
      this.copyStaticFiles();
      
      // 生成构建信息
      this.generateBuildInfo();
      
      // 生成图标（如果不存在）
      this.generateIcons();
      
      // 优化文件
      this.optimizeFiles();
      
      console.log('✅ 构建完成！');
      console.log(`📁 输出目录: ${this.distDir}`);
      this.printBuildSummary();
      
    } catch (error) {
      console.error('❌ 构建失败:', error.message);
      process.exit(1);
    }
  }

  // 创建构建目录
  createBuildDir() {
    if (fs.existsSync(this.distDir)) {
      fs.rmSync(this.distDir, { recursive: true });
    }
    fs.mkdirSync(this.distDir, { recursive: true });
    console.log('📁 创建构建目录');
  }

  // 注入配置到应用文件
  async injectConfig() {
    console.log('🔧 注入构建配置...');
    
    const appJsPath = path.join(this.sourceDir, 'app.js');
    let appJs = fs.readFileSync(appJsPath, 'utf8');
    
    // 替换占位符
    appJs = appJs.replace(
      'const COMPILATION_KEY = "{{COMPILATION_KEY}}";',
      `const COMPILATION_KEY = "${this.buildConfig.compilationKey}";`
    );
    
    appJs = appJs.replace(
      'const VERSION_ID = "{{VERSION_ID}}";',
      `const VERSION_ID = "${this.buildConfig.versionId}";`
    );
    
    appJs = appJs.replace(
      'const DISTRIBUTION = "{{DISTRIBUTION}}";',
      `const DISTRIBUTION = "${this.buildConfig.distribution}";`
    );
    
    // 写入构建后的文件
    fs.writeFileSync(path.join(this.distDir, 'app.js'), appJs);
    
    // 更新 manifest.json 中的版本信息
    const manifestPath = path.join(this.sourceDir, 'manifest.json');
    const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
    manifest.name = `SimpleNote ${this.buildConfig.versionId}`;
    manifest.short_name = `SimpleNote ${this.buildConfig.versionId.split('.')[0]}`;
    fs.writeFileSync(path.join(this.distDir, 'manifest.json'), JSON.stringify(manifest, null, 2));
    
    console.log('✅ 配置注入完成');
  }

  // 复制静态文件
  copyStaticFiles() {
    console.log('📋 复制静态文件...');
    
    const filesToCopy = [
      'index.html',
      'style.css',
      'sw.js'
    ];
    
    filesToCopy.forEach(file => {
      const src = path.join(this.sourceDir, file);
      const dest = path.join(this.distDir, file);
      
      if (fs.existsSync(src)) {
        fs.copyFileSync(src, dest);
        console.log(`  ✓ ${file}`);
      } else {
        console.warn(`  ⚠️ ${file} 不存在`);
      }
    });
    
    // 复制图标目录
    const iconsDir = path.join(this.sourceDir, 'icons');
    if (fs.existsSync(iconsDir)) {
      const distIconsDir = path.join(this.distDir, 'icons');
      fs.mkdirSync(distIconsDir, { recursive: true });
      
      const iconFiles = fs.readdirSync(iconsDir);
      iconFiles.forEach(file => {
        const src = path.join(iconsDir, file);
        const dest = path.join(distIconsDir, file);
        fs.copyFileSync(src, dest);
        console.log(`  ✓ icons/${file}`);
      });
    } else {
      console.warn('  ⚠️ icons 目录不存在');
    }
    
    console.log('✅ 静态文件复制完成');
  }

  // 生成构建信息
  generateBuildInfo() {
    console.log('📊 生成构建信息...');
    
    const buildInfo = {
      version: this.buildConfig.versionId,
      distribution: this.buildConfig.distribution,
      buildTime: this.buildConfig.buildTime,
      buildId: this.buildConfig.buildId,
      compilationKeyHash: crypto.createHash('sha256')
        .update(this.buildConfig.compilationKey)
        .digest('hex'),
      features: [
        '多账户支持',
        '数据加密',
        'Git 同步',
        'PWA 支持',
        '离线使用'
      ],
      supportedPlatforms: [
        'GitHub',
        'Gitee'
      ],
      buildEnvironment: {
        nodeVersion: process.version,
        platform: process.platform,
        arch: process.arch
      }
    };
    
    fs.writeFileSync(
      path.join(this.distDir, 'build-info.json'),
      JSON.stringify(buildInfo, null, 2)
    );
    
    // 生成版本文件
    fs.writeFileSync(
      path.join(this.distDir, 'version.txt'),
      this.buildConfig.versionId
    );
    
    console.log('✅ 构建信息生成完成');
  }

  // 生成图标（如果不存在）
  generateIcons() {
    console.log('🎨 检查图标文件...');
    
    const iconsDir = path.join(this.distDir, 'icons');
    if (!fs.existsSync(iconsDir)) {
      fs.mkdirSync(iconsDir, { recursive: true });
    }
    
    const requiredIcons = [
      { name: 'icon-192.png', size: 192 },
      { name: 'icon-512.png', size: 512 }
    ];
    
    requiredIcons.forEach(icon => {
      const iconPath = path.join(iconsDir, icon.name);
      if (!fs.existsSync(iconPath)) {
        console.log(`  ⚠️ ${icon.name} 不存在，将生成占位图标`);
        this.generatePlaceholderIcon(iconPath, icon.size);
      } else {
        console.log(`  ✓ ${icon.name}`);
      }
    });
  }

  // 生成占位图标
  generatePlaceholderIcon(iconPath, size) {
    // 这里应该生成一个简单的 SVG 图标并转换为 PNG
    // 为了简化，我们创建一个简单的文本文件作为占位符
    const placeholderContent = `# SimpleNote Icon Placeholder
# Size: ${size}x${size}
# This is a placeholder for the actual icon.
# Please replace with a proper PNG icon.`;
    
    fs.writeFileSync(iconPath.replace('.png', '.txt'), placeholderContent);
  }

  // 优化文件
  optimizeFiles() {
    console.log('⚡ 优化文件...');
    
    // 压缩 HTML
    this.minifyHTML();
    
    // 压缩 CSS
    this.minifyCSS();
    
    // 压缩 JavaScript
    this.minifyJS();
    
    console.log('✅ 文件优化完成');
  }

  // 压缩 HTML
  minifyHTML() {
    const htmlPath = path.join(this.distDir, 'index.html');
    let html = fs.readFileSync(htmlPath, 'utf8');
    
    // 简单的 HTML 压缩
    html = html
      .replace(/\s+/g, ' ')
      .replace(/>\s+</g, '><')
      .trim();
    
    fs.writeFileSync(htmlPath, html);
    console.log('  ✓ HTML 压缩完成');
  }

  // 压缩 CSS
  minifyCSS() {
    const cssPath = path.join(this.distDir, 'style.css');
    let css = fs.readFileSync(cssPath, 'utf8');
    
    // 简单的 CSS 压缩
    css = css
      .replace(/\/\*[\s\S]*?\*\//g, '') // 删除注释
      .replace(/\s+/g, ' ') // 压缩空白
      .replace(/;\s*}/g, '}') // 删除分号
      .replace(/{\s*/g, '{') // 压缩大括号
      .replace(/;\s*/g, ';') // 压缩分号
      .trim();
    
    fs.writeFileSync(cssPath, css);
    console.log('  ✓ CSS 压缩完成');
  }

  // 压缩 JavaScript
  minifyJS() {
    const jsPath = path.join(this.distDir, 'app.js');
    let js = fs.readFileSync(jsPath, 'utf8');
    
    // 简单的 JavaScript 压缩（跳过，避免语法错误）
    // js = js
    //   .replace(/\/\*[\s\S]*?\*\//g, '') // 删除块注释
    //   .replace(/\/\/.*$/gm, '') // 删除行注释
    //   .replace(/\s+/g, ' ') // 压缩空白
    //   .replace(/;\s*/g, ';') // 压缩分号
    //   .trim();
    
    // fs.writeFileSync(jsPath, js);
    console.log('  ✓ JavaScript 跳过压缩（避免语法错误）');
  }

  // 打印构建摘要
  printBuildSummary() {
    const files = fs.readdirSync(this.distDir, { recursive: true });
    const totalSize = this.calculateDirectorySize(this.distDir);
    
    console.log('\n📊 构建摘要:');
    console.log(`📁 文件数量: ${files.length}`);
    console.log(`💾 总大小: ${this.formatBytes(totalSize)}`);
    console.log(`🔑 编译密钥: ${this.buildConfig.compilationKey.substring(0, 8)}...`);
    console.log(`📦 分发类型: ${this.buildConfig.distribution}`);
    
    console.log('\n📋 文件列表:');
    files.forEach(file => {
      const filePath = path.join(this.distDir, file);
      const stats = fs.statSync(filePath);
      const size = this.formatBytes(stats.size);
      console.log(`  ${file} (${size})`);
    });
  }

  // 计算目录大小
  calculateDirectorySize(dir) {
    let totalSize = 0;
    
    const files = fs.readdirSync(dir, { recursive: true });
    files.forEach(file => {
      const filePath = path.join(dir, file);
      const stats = fs.statSync(filePath);
      if (stats.isFile()) {
        totalSize += stats.size;
      }
    });
    
    return totalSize;
  }

  // 格式化字节大小
  formatBytes(bytes) {
    if (bytes === 0) return '0 B';
    
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }
}

// 构建配置
const buildConfigs = {
  development: {
    COMPILATION_KEY: 'dev-key-2024',
    VERSION_ID: 'v1.0.0-dev',
    DISTRIBUTION: 'development'
  },
  production: {
    COMPILATION_KEY: 'prod-key-2024',
    VERSION_ID: 'v1.0.0',
    DISTRIBUTION: 'production'
  },
  enterprise: {
    COMPILATION_KEY: 'enterprise-key-2024',
    VERSION_ID: 'v1.0.0-enterprise',
    DISTRIBUTION: 'enterprise'
  }
};

// 主函数
async function main() {
  const args = process.argv.slice(2);
  const buildType = args[0] || 'development';
  
  if (buildType in buildConfigs) {
    const config = buildConfigs[buildType];
    process.env.COMPILATION_KEY = config.COMPILATION_KEY;
    process.env.VERSION_ID = config.VERSION_ID;
    process.env.DISTRIBUTION = config.DISTRIBUTION;
  }
  
  const buildManager = new BuildManager();
  await buildManager.build();
}

// 如果直接运行此脚本
if (require.main === module) {
  main().catch(console.error);
}

module.exports = BuildManager;
